package com.atguigu.gmall.common.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 钟涛
 * @version 1.0
 * @description: TODO
 * @date 2021/12/22 14:17
 */

@Configuration
public class FeignCommonConfig {
    @Bean
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                HttpServletRequest request = requestAttributes.getRequest();
                String userId = request.getHeader("userId");
                String userTempId = request.getHeader("userTempId");
                if(!StringUtils.isEmpty(userId)){
                    template.header("userId",userId);
                }
                if(!StringUtils.isEmpty(userTempId)){
                    template.header("userTempId",userTempId);
                }
            }
        };
    }
}
